<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 16/8/6
 * Time: 11:37
 */

namespace app\weixin\services;


use app\common\model\Donation;
use app\common\util\weixin\OAuth;

class WxpayService
{
    public function createNewOrderNo()
    {
        $no = ccnn_build_orderno();
        if (Donation::instance()->where(['order_no' => $no])->count() > 0) {
            return $this->createNewOrderNo();
        }
        return $no;
    }

    public function getPayInfo($money, $attach = null, $title = '珊瑚公益')
    {
        try {
//            $money = 1;
            $orderno = $this->createNewOrderNo();
            require_once APP_PATH . '../lib/wxpayapi/lib/WxPay.JsApiPay.php';
            //①、获取用户openid
            $tools = new \JsApiPay();
            $openId = OAuth::getOpenid();

            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($title);
            if (!empty($attach) && is_array($attach)) {
                $attach = json_encode($attach);
            }
            $input->SetAttach($attach);
            $input->SetOut_trade_no($orderno);
            $input->SetTotal_fee($money);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("zqcdiy");
            $input->SetNotify_url(U('weixin/wxpay/payNotify', '', true, true));
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);

            $order = \WxPayApi::unifiedOrder($input);

            if (empty($order) || $order['return_code'] == 'FAIL') {
                return ['error' => 1, 'msg' => $order['return_msg']];
            }
            $jsApiParameters = $tools->GetJsApiParameters($order);
            return ['error' => 0, 'info' => $jsApiParameters];
        } catch (\Exception $ex) {
            return ['error' => 1, 'msg' => $ex->getMessage()];
        }


    }


    public function payNotify()
    {
        $notify = new WxpayNotifyService();
        $notify->Handle(false);
    }
}